<template>
  <div>
    <!-- 面包屑导航/封装 -->
    <crumbs secondTitle="用户管理" thirdTitle="用户列表"></crumbs>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryParams.query"
            clearable
            @clear="loadUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="loadUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="editBtn()">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="switchChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editBtn(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delUser(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <change
        :total="total"
        :queryParams="queryParams"
        @size="handleSizeChange"
        @current="handleCurrentChange"
      ></change>
    </el-card>
    <!-- 添加用户对话框 -->
    <!-- 添加修改对话框 -->

    <add-edit-dialog
      :title="title"
      :dialogVisible.sync="dialogVisible"
      :editFrom="editFrom"
    />

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      @close="closeUser"
      :visible.sync="allotDialog"
      width="50%"
    >
      <div>
        <p>当前用户名：{{ userInfo.username }}</p>
        <p>当前角色：{{ userInfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="rolesUserList" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allotDialog = false">取 消</el-button>
        <el-button type="primary" @click="confirmUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import addEditDialog from './addEditDialog'
import {
  getUserList,
  updateUserState,
  addUser,
  editUser,
  delUserInfo,
  getRolesList,
  allotUserPermiss
} from '@/api/users'
export default {
  name: 'User',
  components: {
    addEditDialog
  },
  data() {
    return {
      userList: [],
      queryParams: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      total: 0,
      currentPage4: 4,
      // 对话框的显示与隐藏
      dialogVisible: false,
      // 对话框数据绑定
      addFrom: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 修改用户的默认值
      editDialog: false,
      // 查询到的用户信息对象
      editFrom: {},
      // 修改用户的验证规则
      editFromRules: {},
      title: '',
      // 控制分配角色弹出框
      allotDialog: false,
      // 存储用户信息
      userInfo: {},
      // 所有角色的数据
      rolesList: [],
      // 已选中的角色 ID 值
      rolesUserList: ''
    }
  },
  methods: {
    // 清空分配角色对话框
    closeUser() {
      // debugger
      this.rolesUserList = ''
      this.userInfo = {}
    },
    // 分配用户角色（权限管理）
    async confirmUser() {
      if (!this.rolesUserList) {
        return this.$message.errorr('请选择分配的角色！')
      }
      const res = await allotUserPermiss(this.userInfo.id, this.rolesUserList)
      if (res.meta.status !== 200) {
        this.$message.error('设置角色失败')
      }
      this.$message.success('设置角色成功')
      this.loadUserList()
      this.allotDialog = false
    },
    // 分配角色
    async setRole(val) {
      this.userInfo = val
      const res = await getRolesList()
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色数据失败')
      }
      this.rolesList = res.data
      this.allotDialog = true
    },
    updateList() {
      this.dialogVisible = false
      this.loadUserList()
    },
    // 监听 switch 开关
    async switchChange(userInfo) {
      const res = await updateUserState(userInfo)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('修改状态失败')
      }
      this.$message.success('更新状态成功')
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.queryParams.pagesize = val
      this.loadUserList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.queryParams.pagenum = val
      this.loadUserList()
    },
    async loadUserList() {
      const res = await getUserList(this.queryParams)
      // console.log(res)
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 添加用户校验
    addUser() {
      this.$refs.addFromRef.validate(async valid => {
        if (!valid) return
        const res = await addUser(this.addFrom)
        if (res.meta.status === 201) {
          this.$message.success('添加用户成功')
          this.dialogVisible = false
          this.loadUserList()
        } else {
          this.$message.error('添加用户失败')
        }
      })
    },
    // 修改用户信息
    async editBtn(id) {
      if (id) {
        this.title = '修改用户信息'
        const res = await editUser(id)
        if (res.meta.status !== 200) {
          this.$message.error('查询用户失败')
        }
        this.editFrom = res.data
      } else {
        this.editFrom = {}
        this.title = '添加用户'
      }
      console.log(this.editFrom, 9999999)
      this.dialogVisible = true
    },
    // 删除用户
    async delUser(id) {
      const delInfo = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (delInfo !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const res = await delUserInfo(id)
      if (res.meta.status === 200) {
        this.$message.success('删除用户成功')
        this.loadUserList()
      }
    }
  },
  mounted() {
    this.loadUserList()
  }
}
</script>
